#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <string.h>
using namespace std;
void Usage(string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);

    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    socklen_t len = sizeof(server);

    while (true)
    {

        bool isBreaking = false;
        int cnt = 10;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        do
        {
            int con = connect(sockfd, (const struct sockaddr *)(&server), len);
            if (con < 0)
            {
                isBreaking = true;
                cnt--;
                cerr << "connect is  Reconnect.....:" << cnt << endl;
                sleep(2);
            }
            else
            {
                cout << "server connect success" << endl;
                break;
            }

        } while (cnt && isBreaking);
        if (cnt == 0)
        {
            break;
        }
        char buffer[4096];
        string message;

        while (true)
        {
            cout << "please Enter@:" << endl;
            getline(cin, message);
            ssize_t n = write(sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                break;
            }
            else if (n > 0)
            {
                ssize_t s = read(sockfd, buffer, sizeof(buffer));
                if (s > 0)
                {
                    buffer[s] = 0;
                    cout << buffer << endl;
                }
                else if (s == 0)
                {
                    break;
                }
            }
        }
        close(sockfd);
    }

    return 0;
}